package run.siyuan.jdk.高并发;

/**
 * @className: VisibilityTest
 * @Description: TODO 可见性问题深入分析
 * @author: siyuan
 * @date: 2022/11/8 09:52
 */
public class VisibilityTest {

//    private boolean flag = true;
//    private volatile boolean flag = true;
    private boolean flag = true;

    public void refresh(){
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag");
    }

    public void load(){
        System.out.println(Thread.currentThread().getName() + "开始执行...");
        int i = 0;
        while (flag){
            i++;

        }
        System.out.println(Thread.currentThread().getName() + "跳出循环... i="+i);
    }

    public static void main(String[] args) throws InterruptedException {
        VisibilityTest test = new VisibilityTest();
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        Thread.sleep(1000L);

        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();
    }

}
